package logic

import (
	"context"
	"encoding/json"
	"manuscriptservice/manuscriptservicerpc/internal/svc"
	"manuscriptservice/manuscriptservicerpc/manuscriptservicerpc"
	"manuscriptservice/model/cache"
	"manuscriptservice/model/mysql"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type ManuscriptListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewManuscriptListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ManuscriptListLogic {
	return &ManuscriptListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ManuscriptListLogic) ManuscriptList(in *manuscriptservicerpc.ManuscriptListRequest) (*manuscriptservicerpc.ManuscriptListResponse, error) {
	// todo: add your logic here and delete this line
	var list []*manuscriptservicerpc.ManuscriptList
	result, _ := cache.Rdb.Get(l.ctx, "list").Result()
	if result == "" {
		var err error
		list, err = mysql.ListManuscript(mysql.DB)
		if err != nil {
			return nil, err
		}
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(l.ctx, "list", jsonData, time.Minute*120)
	} else {
		json.Unmarshal([]byte(result), &list)
	}

	return &manuscriptservicerpc.ManuscriptListResponse{
		List: list,
	}, nil
}
